<template>
    <Dialog
      :show="dialogConfig.show"
      :title="dialogConfig.title"
      :buttons="dialogConfig.buttons"
      :showCancel="true"
      @close="dialogConfig.show = false"
      width="1400px"
    >
    <el-container class="main-container">
    <el-container class="content-wrapper">
      <!-- 左侧聊天区 -->
      <el-main class="chat-main">
        <div class="message-container" ref="messageBox">
          <div
            v-for="(msg, index) in messages"
            :key="index"
            class="message-item"
            :class="{ 'my-message': parseInt(msg.sendUserId, 10) === parseInt(currentUser.userId, 10) }"
          >
            <div class="message-meta">
              <span class="sender">{{ msg.sendUserNickName }}</span>
              <span class="time">{{ formatTimestamp(msg.sendTime) }}</span>
            </div>
            <div class="message-content">{{ msg.messageContent }}</div>
          </div>
        </div>
        <div class="input-wrapper">
          <el-input
            v-model="newMessage"
            placeholder="输入消息..."
            @keyup.enter="sendMessage"
            clearable
          >
            <template #append>
              <el-button
                type="primary"
                @click="sendMessage"
                :disabled="!newMessage.trim()"
              >
                发送
              </el-button>
            </template>
          </el-input>
        </div>
      </el-main>
      <el-aside width="300px" class="member-aside">
        <el-card class="member-card">
          <template #header>
            <div class="card-title">
              小组成员（{{ members.length }}人）
              <el-button
              type="primary"
              size="small"
              @click="toggleAddSection"
            >
              {{ showAddSection ? '取消添加' : '添加成员' }}
            </el-button>
            </div>
          </template>

           <!-- 添加成员区域 -->
          <div v-if="showAddSection" class="add-section">
            <el-input
              v-model="searchQuery"
              placeholder="搜索用户..."
              clearable
              @input="handleSearch"
              class="search-input"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>

            <div class="search-results">
              <div
                v-for="user in searchResults"
                :key="user.userId"
                class="user-item"
                :class="{ 'selected': selectedUser?.userId === user.userId }"
                @click="selectUser(user)"
              >
                <el-avatar :size="40" :src="proxy.globalInfo.imageUrl + user.avatar" />
                <div class="user-info">
                  <span class="user-name">{{ user.username }}</span>
                </div>
              </div>
            </div>
            <el-button
              type="success"
              class="confirm-btn"
              :disabled="!selectedUser"
              @click="addToGroup"
            >
              确认添加
            </el-button>
          </div>
          <div v-else
            v-for="member in members"
            :key="member.id"
            class="member-item"
          >
            <el-avatar :size="40" :src="proxy.globalInfo.imageUrl+member.avatar" />
            <div class="member-details">
              <div class="member-name">{{ member.username }}</div>
              <div class="member-status">
                <el-tag
                  size="small"
                  :type="member.online ? 'success' : 'info'"
                >
                  {{ member.online ? '在线' : '离线' }}
                </el-tag>
                <span class="member-role">{{ member.role==1?'管理员':'群成员'}}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-aside>
    </el-container>
    </el-container>
    </Dialog>
  </template>
  <script setup>
  import { dataType } from "element-plus/es/components/table-v2/src/common.mjs";
import { ref,
     reactive,
    onMounted ,
    computed ,
    getCurrentInstance,
    nextTick } from "vue";
  const { proxy } = getCurrentInstance();

  const api = {
    saveAccount: "/group/add",
    loadMenberInfo: "/group/loadGroupMember",
    loadUserList:"/userInfo/loadUserList",
    loadMessageList:"/chat/loadMessageList",

  };

  const dialogConfig = ref({
    show: false,
    title: "小组讨论",

  });


  function formatTimestamp(timestamp) {
    const date = new Date(timestamp);

    // 获取年、月、日、时、分、秒
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');

    // 返回格式化后的日期字符串
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

  // 添加成员数据
const members = ref([
  {
    id: 1,
    name: '张三',
    role: '组长',
    avatar: 'https://example.com/avatar1.jpg',
    online: true
  },
  {
    id: 2,
    name: '李四',
    role: '组员',
    avatar: 'https://example.com/avatar2.jpg',
    online: true
  },
  // 更多成员...
  ])

  const loadMenberInfo = async (groupId) => {
    const result = await proxy.Request({
      url: api.loadMenberInfo,
      params: {
         groupId: groupId,
      }
    }
  )
  if(!result){
    return;
  }
  members.value=result.data;
}


  const currenrGroupId=ref(null);
  // 加载群聊消息
  const loadGroupMessage=async(groupId)=>{
    const result = await proxy.Request({
      url: api.loadMessageList,
      params: {
         groupId: groupId,
      }
    }
  )
  if(!result){
    return;
  }
  messages.value=result.data;
  }

  const show = (data) => {
    dialogConfig.value.show = true;
    nextTick(() => {
      loadGroupMessage(data);
      loadMenberInfo(data);
      currenrGroupId.value=data;
    });
  };

  defineExpose({
    show,
  });

  // 模拟当前用户
  const currentUser = ref(proxy.VueCookies.get("userInfo"))
  const newMessage = ref('')
  const messages = ref([
    {
      sender: '系统',
      content: '欢迎加入讨论！',
      time: '10:00'
    }
  ])

  // 自动滚动到底部
  const messageContainer = ref(null)
  const scrollToBottom = () => {
    nextTick(() => {
      if (messageContainer.value) {
        messageContainer.value.scrollTop = messageContainer.value.scrollHeight
      }
    })
  }

  // 发送消息
  const sendMessage = async() => {
    if (!newMessage.value.trim()) return
    // messages.value.push({
    //   sender: currentUser.value,
    //   messageContent: newMessage.value.trim(),
    //   sendTime: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
    // })
    let result = await proxy.Request({
       url:"/chat/sendMessage",
       params:{
        messageContent:newMessage.value.trim(),
        contactId:currenrGroupId.value,
        contactType:1,
        status:0,
       }
    })
    if(!result){
      return;
    }
    proxy.Message.success("发送成功");
    newMessage.value = ''
    loadGroupMessage();
    scrollToBottom()
  }

  onMounted(() => {
    scrollToBottom()
  });

// 搜索
// 添加成员相关状态
const showAddSection = ref(false)
const searchQuery = ref('')
const selectedUser = ref(null)
const allUsers = ref([
  {
    id: 101,
    name: '王同学',
    department: '计算机系',
    avatar: 'https://example.com/avatar3.jpg'
  },
  {
    id: 102,
    name: '张老师',
    department: '心理辅导中心',
    avatar: 'https://example.com/avatar4.jpg'
  },
  // 更多模拟用户...
])
const loadAllUserInfo = async () => {
    const result = await proxy.Request({
      url: api.loadUserList,
      params: {
      }
    }
  )
  if(!result){
    return;
  }
  allUsers.value=result.data.list;
}
loadAllUserInfo();



// 计算属性实现搜索功能
const searchResults = computed(() => {
  if (!searchQuery.value) return []
  return allUsers.value.filter(user =>
    user.username.includes(searchQuery.value)
  )
})

// 方法定义
const toggleAddSection = () => {
  showAddSection.value = !showAddSection.value
  searchQuery.value = ''
  selectedUser.value = null
}

const selectUser = (user) => {
  selectedUser.value = user
}

const addToGroup = async() => {
  if (!selectedUser.value) return
  // 检查是否已存在
  const exists = members.value.some(m => m.userId === selectedUser.value.userId)
  if (!exists) {
    members.value.push({
      ...selectedUser.value,
      role: '组员',
      online: true
    })
    //
    let result = await proxy.Request({
       url:"/group/add2Group",
       params:{
        groupId:currenrGroupId.value,
        userId:selectedUser.value.userId,
       }
    })
    if(!result){
      return;
    }
    proxy.Message.success('添加成功')
  } else {
    proxy.Message.warning('该用户已在小组中')
  }
  toggleAddSection()
}
</script>
<style lang="scss" scoped>
  .main-container {
  height: calc(100vh - 200px) ;
}

.app-header {
  background-color: #409EFF;
  color: white;
  padding: 0 24px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.content-wrapper {
  height: calc(100vh - 60px);
}

.chat-main {
  display: flex;
  flex-direction: column;
  padding: 0;
  background-color: #f5f7fa;
}

.message-container {
  flex: 1;
  height: 80%;
  padding: 20px;
  overflow-y: auto;
}


.message-item {
  max-width: 75%;
  margin: 12px 0;
  padding: 12px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0,0,0,0.1);
}

.my-message {
  margin-left: auto;
  background-color: #409EFF;
  color: white;
}

.message-meta {
  display: flex;
  justify-content: space-between;
  font-size: 0.8em;
  margin-bottom: 6px;
  opacity: 0.8;
}

.input-wrapper {
  padding: 20px;
  background: white;
  box-shadow: 0 -2px 6px rgba(0,0,0,0.05);
}

.member-aside {
  border-left: 1px solid #ebeef5;
}

.member-card {
  height: 100%;
  border: none;
  border-radius: 0;
}

.member-item {
  display: flex;
  align-items: center;
  padding: 12px;
  gap: 12px;
  border-bottom: 1px solid #f5f7fa;
}

.member-details {
  flex: 1;
}

.member-status {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 4px;
}

.member-role {
  font-size: 0.8em;
  color: #909399;
}

/* 新增样式 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.add-section {
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  margin-bottom: 15px;
}

.search-input {
  margin-bottom: 15px;
}

.search-results {
  max-height: 300px;
  overflow-y: auto;
  margin-bottom: 15px;
}

.user-item {
  display: flex;
  align-items: center;
  padding: 10px;
  cursor: pointer;
  transition: background-color 0.3s;
  border-radius: 4px;
}

.user-item:hover {
  background-color: #f5f7fa;
}

.user-item.selected {
  background-color: #ecf5ff;
  border: 1px solid #409EFF;
}

.user-info {
  margin-left: 12px;
  line-height: 1.4;
}
.user-name {
  display: block;
  font-weight: 500;
}

.user-department {
  font-size: 0.8em;
  color: #909399;
}

.confirm-btn {
  width: 100%;
  margin-top: 10px;
}
</style>
